import 'package:flutter_admin/api/odoo/res_partner_odoo_api.dart';
import 'package:flutter_admin/models/odoo/res_partner.dart';
import 'package:flutter_admin/pages/common/cry/cry.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/cry_dialog.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/odoo/res_purchase/purchase_qualifications_file/purchase_qualifications_file_list.dart';
import 'package:flutter_admin/pages/odoo/res_purchase/res_purchase_dialog.dart';
import 'package:flutter_admin/pages/odoo/res_purchase/res_purchase_edit.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/utils.dart';

class ResPurchaseList extends StatefulWidget {
  ResPurchaseList({Key? key}) : super(key: key);

  @override
  _ResPurchaseListState createState() => _ResPurchaseListState();
}

class _ResPurchaseListState extends State<ResPurchaseList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  ResPartner resPartner = ResPartner();
  List<ResPartner> selectedList = [];
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
    });
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CryInput(
            width: 160,
            label: '供应商名称',
            value: resPartner.name,
            onSaved: (v) {
              resPartner.name = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('企业类型')),
        DataColumn(label: Text('供应商编码')),
        DataColumn(label: Text('用户名')),
        DataColumn(label: Text('供应商名称')),
        DataColumn(label: Text('供应商简称')),
        DataColumn(label: Text('供应商曾用名称')),
        DataColumn(label: Text('企业性质')),
        DataColumn(label: Text('邮编')),
        DataColumn(label: Text('电子邮件')),
        DataColumn(label: Text('企业电话')),
        DataColumn(label: Text('传真')),
        DataColumn(label: Text('公司办公地址')),
        DataColumn(label: Text('公司网站地址')),
        DataColumn(label: Text('生产工厂地址')),
        DataColumn(label: Text('开户银行')),
        DataColumn(label: Text('银行账号')),
        DataColumn(label: Text('公司法人姓名')),
        DataColumn(label: Text('法人联系方式')),
        DataColumn(label: Text('公司投资人姓名')),
        DataColumn(label: Text('各自投资比例')),
        DataColumn(label: Text('公司成立时间')),
        DataColumn(label: Text('税号')),
        DataColumn(label: Text('注册资金（万元）')),
        DataColumn(label: Text('固定资产（万元）')),
        DataColumn(label: Text('生产规模')),
        DataColumn(label: Text('所属行业')),
        DataColumn(label: Text('行业排序')),
        DataColumn(label: Text('银行资信证明')),
        DataColumn(label: Text('供货区域')),
        DataColumn(label: Text('所属地区')),
        DataColumn(label: Text('QQ')),
        DataColumn(label: Text('信函通讯地址')),
        DataColumn(label: Text('公司营业范围')),
        DataColumn(label: Text('产品品牌')),
        DataColumn(label: Text('业绩简介')),
        DataColumn(label: Text('企业简介')),
      ],
      getCells: (m) {
        ResPartner resPartner = ResPartner.fromMap(m);
        return [
          DataCell(Text(resPartner.businessType == '0'
              ? '供应商'
              : resPartner.businessType == '1'
                  ? '生产商'
                  : '--')),
          DataCell(Text(resPartner.ref ?? '--')),
          DataCell(Text(resPartner.userNameSupplier ?? '--')),
          DataCell(Text(resPartner.name ?? '--')),
          DataCell(Text(resPartner.supplierAbbreviation ?? '--')),
          DataCell(Text(resPartner.usedName ?? '--')),
          DataCell(Text(resPartner.person ?? '--')),
          DataCell(Text(resPartner.zip ?? '--')),
          DataCell(Text(resPartner.email ?? '--')),
          DataCell(Text(resPartner.phone ?? '--')),
          DataCell(Text(resPartner.faxes ?? '--')),
          DataCell(Text(resPartner.officeAddress ?? '--')),
          DataCell(Text(resPartner.website ?? '--')),
          DataCell(Text(resPartner.factoryAddress ?? '--')),
          DataCell(Text(resPartner.bank ?? '--')),
          DataCell(Text(resPartner.bankAccount ?? '--')),
          DataCell(Text(resPartner.primaryContact ?? '--')),
          DataCell(Text(resPartner.mobile ?? '--')),
          DataCell(Text(resPartner.investor ?? '--')),
          DataCell(Text(resPartner.investRatio ?? '--')),
          DataCell(Text(resPartner.regTime ?? '--')),
          DataCell(Text(resPartner.vat ?? '--')),
          DataCell(Text(resPartner.registerMoney != null
              ? resPartner.registerMoney.toString()
              : '--')),
          DataCell(Text(resPartner.fixedAssets != null
              ? resPartner.fixedAssets.toString()
              : '--')),
          DataCell(Text(resPartner.processScale ?? '--')),
          DataCell(Text(resPartner.industryName ?? '--')),
          DataCell(Text(resPartner.industrySort ?? '--')),
          DataCell(Text(resPartner.credibilityLetter ?? '--')),
          DataCell(Text(resPartner.areaName ?? '--')),
          DataCell(Text(resPartner.area ?? '--')),
          DataCell(Text(resPartner.qq ?? '--')),
          DataCell(Text(resPartner.postalAddress ?? '--')),
          DataCell(Text(resPartner.mainBusiness ?? '--')),
          DataCell(Text(resPartner.productBrand ?? '--')),
          DataCell(Text(resPartner.performanceProfile ?? '--')),
          DataCell(Text(resPartner.enterpriseProfile ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        CryButtons.add(context, () => _edit(null)),
        CryButtons.edit(context,
            selectedList.length != 1 ? null : () => _edit(selectedList[0])),
        CryButtons.delete(context,
            selectedList.length < 1 ? null : () => _delete(selectedList)),
        CryButton(
          label: "资质文件",
          iconData: Icons.file_copy,
          onPressed:
          selectedList.length != 1 ? null : () => _purchaseQualificationsFile(selectedList[0])),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          Wrap(
            children: [
              isDisplayDesktop(context) ? form : Container(),
              Padding(
                padding: EdgeInsets.only(top: 24),
                child: isDisplayDesktop(context) ? buttonBar : Container(),
              )
            ],
          ),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _purchaseQualificationsFile(ResPartner? resPartner) async {
    Utils.fullscreenDialog(PurchaseQualificationsFileList(
      suppliercode: resPartner!.ref,
    ),);
  }

  _edit(ResPartner? resPartner) async {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: ResPurchaseEdit(
          resPartner: resPartner,
        ),
      ),
    ).then((v) {
      if (v != null) {
        if(resPartner == null){
          // 新增时回到第一页
          tableKey.currentState?.pageTo(0);
        }
        _loadData();
      }
    });
  }

  _reset() {
    resPartner = ResPartner();
    formKey.currentState!.reset();
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi = await ResPartnerOdooApi.page(
        data: {"page": page, "domainList": resPartner.toDomainList1()});
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _delete(List<ResPartner> selectedList) async {
    cryConfirm(context, S.of(context).confirmDelete, (context) async {
      List ids = selectedList.map((v) {
        return int.parse(v.id!);
      }).toList();
      var result = await ResPartnerOdooApi.removeByIds(ids);
      if (result.success!) {
        _query();
        CryUtils.message(S.of(Cry.context).success);
      }
    });
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: ResPurchaseDialog(),
      ),
    ).then((v) {
      if (v != null) {
        resPartner = v;
        _query();
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<ResPartner>((e) => ResPartner.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.add) {
          _edit(null);
        } else if (v == OperationType.edit) {
          _edit(selectedList[0]);
        } else if (v == OperationType.delete) {
          _delete(selectedList);
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.add,
          child: ListTile(
            leading: const Icon(Icons.add),
            title: Text('添加'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.edit,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.edit),
            enabled: selectedList.length == 1,
            title: Text('修改'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.delete,
          enabled: selectedList.length != 0,
          child: ListTile(
            leading: const Icon(Icons.delete), //Icons.delete
            enabled: selectedList.length != 0,
            title: Text('删除'),
          ),
        ),
      ],
    );
  }
}
